<template>
    <div class="container">
        <header class="navbar">
            <div class="left" @click="goBack">
                <van-icon name="arrow-left" size="20" />
            </div>
            <div class="title">
                <span class="ep_title">{{ store.comic_title }}</span>
                <span class="ep_index">第 {{ store.comic_short_title }} 话</span>
            </div>
            <div class="detail" @click="goToDetail(store.comic_id)">
                详情
            </div>
        </header>
        <div class="content">
            <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad"
                @scroll="onScroll">
                <!-- <van-cell v-for="item in list" :key="item" :title="item" /> -->
                <div v-for="(image, index) in complete_url" :key="index" class="image-box">
                    <van-image :src="image" v-lazy="image"></van-image>
                </div>
            </van-list>
        </div>
        <div class="status">
            <span> {{ getCurrentComicSessionIndex }} /{{ imagesNumber }}</span>
            <span> 第 {{ store.comic_short_title }} 话</span>
        </div>
    </div>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { fetchImg, fetchImgFromToken } from "@/api/index"
import { useStore } from "@/pinia/index"
const store = useStore()
const router = useRouter()
const route = useRoute()
const props = defineProps({
    // 当前章节ID
    id: {
        type: String,
    }
})
import Next from "@/assets/next.png"   //即将进入下一话
import Previous from "@/assets/previous.png"  //即将进入上一话
const isEnd = ref(false) //当前章节是否结束
const loading = ref(true)
const finished = ref(false)
// 当前章节ID
// const chapter_id = computed(() => route.params.id )
const chapter_id = ref(route.params.id || props.id)
// 图片集合
const images = ref([])
// 图片数量
const imagesNumber = computed(() => images.value.length)
// 当前图片索引
const imageIndex = ref(0)
// 当前漫画绘画序列
const getCurrentComicSessionIndex = computed(() => imageIndex.value + 1)
//  真实图片完整URL
const complete_url = ref([])
/* 在现有代码基础上添加以下内容  */
// 添加用于追踪滚动方向和历史记录的响应式变量
const scrollPosition = ref(0)
// 添加当前方向状态
const direction = ref('down') // 'up' 或 'down'
onMounted(async () => {
    loading.value = true
    console.log("onMounted chapter_id:", chapter_id.value)
    await getImg(chapter_id.value) //某一章节全部图片
    console.log("初始化章节第一张图片:", images.value[imageIndex.value]);
    await getImgFromToken(images.value[imageIndex.value]) //初始化章节第一张图片
    loading.value = false
});
// 当前章节全部图片
const getImg = async (chapter_id) => {
    const { data: { images: details } } = await fetchImg(chapter_id)
    // console.log("details:", details)
    // detail 是一个对象数组，每个对象有个属性path，需要提取path的值, 然后将'@660w.jpg'拼接到path值的最后组成新的数组
    // console.log("images:", images.value)
    if (details.length > 0) {
        images.value = details.map(item => item.path + '@660w.jpg') //当前章节全部图片
    } else {
        images.value = []
    }
};
// 图片真实URL
// const getImgFromToken = async (image_path, isEnd) => {
//     if (image_path) {
//         //console.log("image_path:", image_path)
//         const { data } = await fetchImgFromToken(image_path)
//         // console.log("data:", data)
//         console.log(`第${imageIndex.value + 1}张图片完整图片URL:`, data[0].complete_url)
//         if (isEnd && data) {
//             complete_url.value.push(...data[0].complete_url, Next)
//         } else if (data) {
//             complete_url.value.push(data[0].complete_url)
//         }
//     } else {
//         console.log('图片不存在')
//     }
//}
// 修改getImgFromToken函数以支持Previous图片显示
const getImgFromToken = async (image_path, isEnd) => {
    if (image_path) {
        const { data } = await fetchImgFromToken(image_path)
        console.log(`第${imageIndex.value + 1}张图片完整图片URL:`, data[0].complete_url)
        if (isEnd && data) {
            // 根据方向显示不同的过渡图片
            if (direction.value === 'down') {
                complete_url.value.push(...data[0].complete_url, Next)
            } else {
                complete_url.value.push(...data[0].complete_url, Previous)
            }
        } else if (data) {
            complete_url.value.push(data[0].complete_url)
        }
    } else {
        console.log('图片不存在')
    }
}
const onScroll = (event) => {
    const currentScrollPosition = event.target.scrollTop || 0
    // 判断滚动方向
    if (currentScrollPosition > scrollPosition.value) {
        direction.value = 'down'
        console.log("滚动方向: 下")
    } else if (currentScrollPosition < scrollPosition.value) {
        direction.value = 'up'
        console.log("滚动方向: 上")
    }
    // 更新滚动位置
    scrollPosition.value = currentScrollPosition
}
// 加载更多图片
// const onLoad = async () => {
//     loading.value = true
//     imageIndex.value++
//     isEnd.value = false;
//     if (imageIndex.value < imagesNumber.value) {
//         await getImgFromToken(images.value[imageIndex.value], isEnd.value)
//         loading.value = false
//     } else {
//         // 当前章节结束
//         console.log('下一章节')
//         imageIndex.value = 0
//         isEnd.value = true;
//         // 获取下一章节ID（只调用一次）
//         const nextChapterId = getNextMenu_id(chapter_id.value)
//         if (nextChapterId) {
//             chapter_id.value = nextChapterId
//             // 获取下一章节全部图片
//             await getImg(chapter_id.value)
//             // 加载下一章节第一张图片
//             if (images.value.length > 0) {
//                 await getImgFromToken(images.value[imageIndex.value], isEnd.value)
//                 loading.value = false
//             } else {
//                 finished.value = true
//             }
//         } else {
//             // 没有下一章节了
//             finished.value = true
//             loading.value = false
//         }
//     }
// }
const onLoad = async () => {
    loading.value = true
    // 保存之前的索引用于判断方向
    const previousIndex = imageIndex.value
    imageIndex.value++
    isEnd.value = false;
    // 判断滚动方向
    if (imageIndex.value < previousIndex) {
        direction.value = 'up'
    } else {
        direction.value = 'down'
    }
    if (imageIndex.value < imagesNumber.value) {
        await getImgFromToken(images.value[imageIndex.value], isEnd.value)
        loading.value = false
    } else {
        if (direction.value === 'down') {
            // 下滑到下一话逻辑
            console.log('下一章节')
            imageIndex.value = 0
            isEnd.value = true;
            // 获取下一章节ID
            const nextChapterId = getNextMenu_id(chapter_id.value)
            if (nextChapterId) {
                chapter_id.value = nextChapterId
                // 获取下一章节全部图片
                await getImg(chapter_id.value)
                // 加载下一章节第一张图片
                if (images.value.length > 0) {
                    await getImgFromToken(images.value[imageIndex.value], isEnd.value)
                    loading.value = false
                } else {
                    finished.value = true
                }
            } else {
                // 没有下一章节了
                finished.value = true
                loading.value = false
            }
        } else {
            // 上滑到上一话逻辑
            console.log('上一章节')
            // 获取上一章节ID
            const previousChapterId = getPreviousMenu_id(chapter_id.value)
            if (previousChapterId) {
                chapter_id.value = previousChapterId
                // 获取上一章节全部图片
                await getImg(chapter_id.value)
                // 设置索引为最后一张图片
                imageIndex.value = images.value.length - 1
                if (images.value.length > 0) {
                    await getImgFromToken(images.value[imageIndex.value], isEnd.value)
                    loading.value = false
                } else {
                    finished.value = true
                }
            } else {
                // 没有上一章节了
                finished.value = true
                loading.value = false
            }
        }
    }
}
//传入当前id  获取 下一章节id
// const getNextMenu_id = (current_id) => {
//     // const current_id = props.id  //当前章节id
//     console.log("store.chapters_id", store.chapters_id)
//     // 统一转换为数字类型进行比较
//     const current_id_index = store.chapters_id.findIndex((item_id) => {
//         return Number(item_id) === Number(current_id)
//     })
//     console.log("current_id ", current_id)
//     console.log("current_id_index ", current_id_index)
//     if (current_id_index === -1) {
//         console.warn("当前章节ID在章节列表中未找到")
//         return null
//     }
//     if (current_id_index === store.chapters_id.length - 1) {
//         // 已经是最后一章
//         return null
//     }
//     const next_id_index = current_id_index + 1;
//     console.log("下一章节索引:", next_id_index)
//     console.log("下一章节ID:", store.chapters_id[next_id_index])
//     //更新当前漫画会话数
//     store.set_comic_short_title(store.comic_sessions[next_id_index])
//     return store.chapters_id[next_id_index];
// }
// 修改getNextMenu_id函数，添加current_id参数
const getNextMenu_id = (current_id) => {
    console.log("store.chapters_id", store.chapters_id)
    // 统一转换为数字类型进行比较
    const current_id_index = store.chapters_id.findIndex((item_id) => {
        return Number(item_id) === Number(current_id)
    })
    console.log("current_id ", current_id)
    console.log("current_id_index ", current_id_index)
    if (current_id_index === -1) {
        console.warn("当前章节ID在章节列表中未找到")
        return null
    }
    if (current_id_index === store.chapters_id.length - 1) {
        // 已经是最后一章
        return null
    }
    const next_id_index = current_id_index + 1;
    console.log("下一章节索引:", next_id_index)
    console.log("下一章节ID:", store.chapters_id[next_id_index])
    //更新当前漫画会话数
    store.set_comic_short_title(store.comic_sessions[next_id_index])
    return store.chapters_id[next_id_index];
}
// 获取 前一章节id
// 完善getPreviousMenu_id函数
const getPreviousMenu_id = (current_id) => {
    console.log("store.chapters_id", store.chapters_id)
    // 统一转换为数字类型进行比较
    const current_id_index = store.chapters_id.findIndex((item_id) => {
        return Number(item_id) === Number(current_id)
    })
    console.log("current_id ", current_id)
    console.log("current_id_index ", current_id_index)
    if (current_id_index === -1) {
        console.warn("当前章节ID在章节列表中未找到")
        return null
    }
    if (current_id_index === 0) {
        // 已经是第一章
        return null
    }
    const previous_id_index = current_id_index - 1;
    console.log("上一章节索引:", previous_id_index)
    console.log("上一章节ID:", store.chapters_id[previous_id_index])
    //更新当前漫画会话数
    store.set_comic_short_title(store.comic_sessions[previous_id_index])
    return store.chapters_id[previous_id_index];
}
const goBack = () => {
    router.go(-1)
};
const goToDetail = (id) => {
    router.push({ path: `/detail/${id}` })
};
</script>
<style scoped lang="scss">
.container {
    position: relative;

    .navbar {
        position: fixed;
        top: 0;
        left: 0;
        z-index: 10;
        height: 44px;
        width: 100%;
        background-color: #000;
        color: #fff;
        display: flex;
        align-items: center;
        padding: 0 10px;

        .left {
            font-size: 16px;
        }

        .title {
            margin-left: 20px;

            .ep_title {
                font-size: 16px;
            }

            .ep_index {
                font-size: 12px;
                margin-left: 10px;
            }
        }

        .detail {
            margin-left: 20px;
            font-size: 12px;
            border: 1px solid #fb7299;
            border-radius: 4px;
            width: 60px;
            text-align: center;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            box-sizing: border-box;
        }
    }

    .content {
        margin: 0;

        .image-box {
            font-size: 0;
        }
    }

    .status {
        position: fixed;
        bottom: 0;
        right: 0;
        background-color: rgba(0, 0, 0, 0.6);
        color: #fff;
        display: flex;
        align-items: center;
        gap: 10px;
        justify-content: flex-start;
        font-size: 14px;
        border-top-left-radius: 4px;
        padding: 3px 6px;
    }
}
</style>